import {
  Inject,
  JoinPoint,
  MidwayDecoratorService,
  Provide,
  Scope,
  ScopeEnum,
} from '@midwayjs/core';
import { JSON_FORMAT } from '../decorators/json.decorator';
import { json } from '../utils/functions';

@Provide()
@Scope(ScopeEnum.Singleton)
export default class DecoratorService {
  @Inject()
  decoratorService: MidwayDecoratorService;
  register() {
    this.decoratorService.registerMethodHandler(JSON_FORMAT, options => {
      return {
        around: async (joinPoint: JoinPoint) => {
          // 拿到格式化参数
          const format = options.metadata.format || json;

          // 执行原方法
          const result = await joinPoint.proceed(...joinPoint.args);

          // 返回执行结果
          return format(result);
        },
      };
    });
  }
}
